<template>
  <Upload
    name="file"
    v-model:fileList="localCover"
    list-type="picture-card"
    :show-upload-list="false"
    class="avatar-uploader"
    :data="getUploadData"
    :max-count="1"
    :action="ossData?.host"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <div v-if="imgPic && imgPic.length > 0">
      <img :src="imgPic[0].url" alt="背景图" style="width: 100%" />
    </div>
    <div v-else>
      <PlusOutlined />
      <div class="ant-upload-text">上传图片</div>
    </div>
  </Upload>
</template>
<script setup>
  import { message, Upload } from 'ant-design-vue';
  import { getOssApi } from '@/api/oss/index';
  import { onMounted, ref, watch } from 'vue';
  import { PlusOutlined } from '@ant-design/icons-vue';

  // @eslint-ignore
  const props = defineProps(['imgPic']);

  console.log('props.imgPic', props.imgPic);
  onMounted(() => {
    getOssInfo();
  });

  const localCover = ref();
  // 同步父组件数据到局部变量
  watch(
    () => props.imgPic,
    (newVal) => {
      localCover.value = newVal || [];
    },
    { immediate: true },
  );

  const ossData = ref({});
  const getOssInfo = async () => {
    const data = await getOssApi.getOssInfo();
    ossData.value = data;
  };
  const getKey = (file) => {
    const key = `${ossData.value?.dir}${file.uid}${file.name}`;
    const url = `${ossData.value?.host}/${key}`;
    return { key, url };
  };
  const getUploadData = (file) => {
    return {
      key: getKey(file).key,
      policy: ossData.value.policy,
      OSSAccessKeyId: ossData.value.accessId,
      Signature: ossData.value.signature,
    };
  };

  // 使用defineEmits注册一个自定义事件
  const emit = defineEmits(['changeCover']);
  const handleChange = ({ file, fileList }) => {
    if (file.status === 'done') {
      const responseUrl = getKey(file).url; // 假设 OSS 返回 { url: '...' }
      if (responseUrl) {
        file.url = responseUrl; // 更新实际 URL
      }
    }
    const files = fileList.map((f) => ({
      uid: f.uid, // 唯一标识
      name: f.name, // 文件名
      status: f.status, // 上传状态
      url: f.url || getKey(f).url,
    }));
    emit('changeCover', files);
  };
  const beforeUpload = async (file) => {
    if (!ossData.value) return false;
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('图片大小不能超过 10MB！');
      return false;
    }
    const expire = Number(ossData.value.expire) * 1000;
    if (expire < Date.now()) {
      await getOssInfo();
    }
    return file;
  };
</script>
